package com.baizhi.action;

import com.baizhi.entity.User;
import com.baizhi.service.UserService;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpSession;

@Controller
@Scope("prototype")
public class UserAction {
    private UserService userService;
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    private User u;
    private String userName;
    private String password;
    private String validatecode;

    public String getValidatecode() {
        return validatecode;
    }

    public void setValidatecode(String validatecode) {
        this.validatecode = validatecode;
    }

    public User getU() {
        return u;
    }

    public void setU(User u) {
        this.u = u;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String register(){
        int i = userService.register(u);
        return "registerOk";
    }

    public String login(){
        HttpSession session = ServletActionContext.getRequest().getSession();
        String realCode = (String) session.getAttribute("validatecode");
        if(realCode!=null && realCode.equalsIgnoreCase(validatecode)){
            boolean result = userService.login(userName, password);
            if(result){
                u = userService.selectByUserName(userName);
                session.setAttribute("login",u);
                System.out.println(session.getAttribute("login"));
                return "loginOk";
            }else {
                return "loginError";
            }
        }else {
            return "loginError";
        }

    }
    public String exit(){
        ServletActionContext.getRequest().getSession().removeAttribute("login");
        return "loginError";
    }
}
